package com.moli.iov.base.remote.impl;

import com.moli.iov.base.cache.mongodb.AlarmEquipmentRecordService;
import com.moli.iov.base.enums.AlarmTypeEnum;
import com.moli.iov.base.enums.AuthorizedEnum;
import com.moli.iov.base.enums.DictTypeTag;
import com.moli.iov.base.enums.HandlingStatusEnum;
import com.moli.iov.base.model.dto.req.AlarmEquipmentRecordDto;
import com.moli.iov.base.model.dto.req.VehicleBaseReqDto;
import com.moli.iov.base.model.dto.res.AlarmEquipmentRecordResDto;
import com.moli.iov.base.model.mongo.AlarmEquipmentRecord;
import com.moli.iov.base.model.po.VehicleBase;
import com.moli.iov.base.model.po.VehicleBaseAuth;
import com.moli.iov.base.remote.IAlarmEquipmentRecordRemoteService;
import com.moli.iov.base.service.IDictDataService;
import com.moli.iov.base.service.IVehicleBaseAuthService;
import com.moli.iov.base.service.IVehicleBaseService;
import com.moli.iov.model.dto.req.PageExtend;
import com.moli.iov.rest.RestResponse;
import com.moli.iov.util.CommonUtils;
import com.moli.iov.util.JsonUtils;
import com.moli.iov.util.ValidationUtils;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

/**
 * 报警页面
 *
 * @author wanghualin
 * @date 2019-09-27 13:13:10
 */
@Transactional(rollbackFor = Exception.class)
@Service(group = "${service.group}")
@Slf4j
public class IAlarmEquipmentRecordRemoteServiceImpl implements IAlarmEquipmentRecordRemoteService {

  @Autowired
  private AlarmEquipmentRecordService alarmEquipmentRecordService;

  @Autowired
  private IVehicleBaseService iVehicleBaseService;
  @Autowired
  private IDictDataService dictDataService;
  @Autowired
  private IVehicleBaseAuthService baseAuthService;
  @Override
  public PageExtend<AlarmEquipmentRecordResDto> listEquipmentRecord(
      AlarmEquipmentRecordDto dto) {
    log.info( "报警管理-设备变更报警-列表-入参AlarmEquipmentRecordDto:{}", JsonUtils.toJson(dto));
    PageExtend<AlarmEquipmentRecordResDto> recordResDtoPageExtend = alarmEquipmentRecordService.listEquipmentRecord(dto);
    log.info( "报警管理-设备变更报警-列表-出参recordResDtoPageExtend:{}"+JsonUtils.toJson(recordResDtoPageExtend));
    return recordResDtoPageExtend;
  }

  @Override
  public RestResponse updateAlarmEquipmentRecord(AlarmEquipmentRecordDto dto) {
    log.info( "报警管理-设备变更报警-更新-入参AlarmEquipmentRecordDto:{}",JsonUtils.toJson(dto));
    ValidationUtils.validateBean(dto, AlarmEquipmentRecordDto.Update.class);
    AlarmEquipmentRecord alarmEquipmentRecord = alarmEquipmentRecordService
        .getAlarmEquipmentRecord(dto.getAlarmId());
    ValidationUtils.validateBean(alarmEquipmentRecord);
    //只处理未注册报警
    if (alarmEquipmentRecord.getAlarmType() != null
        && alarmEquipmentRecord.getAlarmType().intValue() == AlarmTypeEnum.EQUIPMENT_UNAUTHORIZED
        .getCode()) {
        unauthorizedHandle(dto);
    }
    //设备拆除
    else if(alarmEquipmentRecord.getAlarmType() != null
            && alarmEquipmentRecord.getAlarmType().intValue() == AlarmTypeEnum.EQUIPMENT_REMOVAL
            .getCode()){
      //TODO
    }
    //设备更换
    else if(alarmEquipmentRecord.getAlarmType() != null
            && alarmEquipmentRecord.getAlarmType().intValue() == AlarmTypeEnum.EQUIPMENT_REPLACEMENT
            .getCode()){
       //TODO
    }
    alarmEquipmentRecordService
        .updateAlarmEquipmentRecord(dto.getSysUserId().toString(),
            HandlingStatusEnum.YES.getCode(), dto.getAlarmId());
    RestResponse success = RestResponse.success();
    log.info( "报警管理-设备变更报警-更新-出参AlarmEquipmentRecordDto:{}",JsonUtils.toJson(success));
    return success;
  }

  @Override
  public RestResponse<Boolean> hasAlarmEquipmentRecordByVin(String vin) {

    return RestResponse.success(alarmEquipmentRecordService.hasAlarmEquipmentRecordsByVin(vin));
  }

  /**
   * 未授权解除
   */
   public void unauthorizedHandle(AlarmEquipmentRecordDto dto){
     ValidationUtils.validateBean(dto,AlarmEquipmentRecordDto.UnauthorizedUpdate.class);
     VehicleBase base = iVehicleBaseService
             .getVehicleBaseUnauthorizedByVin(dto.getVin());
     if (base != null) {

       VehicleBaseReqDto vehicleBaseReqDto = new VehicleBaseReqDto();
       CommonUtils.copyProperties(base, vehicleBaseReqDto);
       CommonUtils.copyProperties(dto,vehicleBaseReqDto);
       setBrandAndSeries(vehicleBaseReqDto);
       vehicleBaseReqDto.setAuthorizedStatus(AuthorizedEnum.AUTHORIZED.getCode());
       vehicleBaseReqDto.setGmtModified(new Date());
       vehicleBaseReqDto.setModifiedUser(dto.getSysUserId().toString());
       iVehicleBaseService.updateVehicleBase(vehicleBaseReqDto);
       //添加车辆报警
       saveVehicleBaseAuth(dto);
     }
   }

  /**
   * 添加车辆授权状态 初始化
   * @param dto
   */
  public void saveVehicleBaseAuth(AlarmEquipmentRecordDto dto){
    Date date= Calendar.getInstance().getTime();
    VehicleBaseAuth auth=new VehicleBaseAuth();
    auth.setLoginAuthStatus(AuthorizedEnum.AUTHORIZED.getCode());
    auth.setLostAlarmAuthStatus(AuthorizedEnum.AUTHORIZED.getCode());
    auth.setMileageAlarmAuthStatus(AuthorizedEnum.AUTHORIZED.getCode());
    auth.setTerminalAuthStatus(AuthorizedEnum.AUTHORIZED.getCode());
    auth.setFenceAlarmAuthStatus(AuthorizedEnum.AUTHORIZED.getCode());
    auth.setGmtCreate(date);
    auth.setCreateUser(dto.getSysUserId().toString());
    auth.setVin(dto.getVin());
    baseAuthService.saveVehicleBaseAuth(auth);
   }

   /**
   * 设置品牌 车系 车型
   */
  private void setBrandAndSeries(VehicleBaseReqDto dto) {
    List<DictTypeTag> list = new ArrayList<>();
    list.add(DictTypeTag.VEHICLE_SERIES);
    list.add(DictTypeTag.VEHICLE_TYPE);
    list.add(DictTypeTag.BRAND);
    Map<String, Map<String, String>> dictMaps = dictDataService.getDictMaps(list);
    dto.setVehicleSeriesName(
            dictMaps.get(DictTypeTag.VEHICLE_SERIES.getType()).get(dto.getVehicleSeries()));
    dto.setVehicleTypeName(
            dictMaps.get(DictTypeTag.VEHICLE_TYPE.getType()).get(dto.getVehicleType()));
    dto.setBrandName(dictMaps.get(DictTypeTag.BRAND.getType()).get(dto.getBrand()));
  }
}
